package com.lingo.dingrobotutils.utils;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.lingo.dingrobotutils.model.msgBuilder.MyDingMsgBuilder;
import com.taobao.api.ApiException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;


/**
 * @file: com.lingo.dingRobot.common.util.DingRequestUtils
 * @Description: todo
 * @author: lingo
 * @version: v1.0
 * @date: 2020/3/19 16:22
 * @Company: www.xyb2b.com
 */
@Component
public class DingRequestUtils {

    private static Logger logger = LoggerFactory.getLogger(DingRequestUtils.class);

    private static String ROOT_URL;
    private static String ACCESS_TOKEN;
    private static String URL;
    private static DingTalkClient client;
    private static String SIGN_SECRET;
    private static boolean NEED_SIGN;


    @Value("${robot.rootUrl}")
    public void setRootUrl(String rootUrl) {
        ROOT_URL = rootUrl;
    }

    @Value("${robot.accessToken}")
    public void setAccessToken(String accessToken) {
        ACCESS_TOKEN = accessToken;
    }

    @Value("${robot.needSign:false}")
    public void setNeedSign(boolean needSign) {
        NEED_SIGN = needSign;
    }

    @Value("${robot.signSecret}")
    public void setSignSecret(String signSecret) {
        SIGN_SECRET = signSecret;
    }


    @PostConstruct
    private static void init() {
        if (NEED_SIGN) {
            if (StringUtils.isEmpty(SIGN_SECRET)) {
                throw new RuntimeException("当需要进行 消息加签时,signSecret 不能为空，请正确配置 signSecret");
            } else {
                //尝试加签，看格式是否正确
                try {
                    DingMsgSignUtils.getTimestampSign(System.currentTimeMillis(), SIGN_SECRET);
                } catch (RuntimeException e) {
                    logger.error(e.getLocalizedMessage());
                    throw e;
                }
            }
        } else {
            URL = String.format("%s?access_token=%s", ROOT_URL, ACCESS_TOKEN);
            client = new DefaultDingTalkClient(URL);
        }
    }

    public static boolean sendMsg(OapiRobotSendRequest request) {
        OapiRobotSendResponse response = null;
        DingTalkClient nowClient = getClient();
        try {
            response = nowClient.execute(request);
        } catch (ApiException e) {
            logger.info("访问钉钉api失败！失败code：{},提示信息:{}", e.getErrCode(), e.getErrMsg());
            return false;
        }
        boolean isSuccess = response.isSuccess();
        if (!isSuccess) {
            logger.error("钉钉消息发送失败，失败code：{},失败原因：{}", response.getErrcode(), response.getErrmsg());
        } else {
            logger.info("钉钉消息发送成功！");
        }
        return isSuccess;
    }

    public static boolean sendMsg(MyDingMsgBuilder myDingMsgBuilder) {
        return sendMsg(myDingMsgBuilder.build());
    }

    public static DingTalkClient getClient() {
        if (!NEED_SIGN) {
            return client;
        }
        long timestamp = System.currentTimeMillis();
        URL = String.format("%s?access_token=%s&timestamp=%s&sign=%s", ROOT_URL, ACCESS_TOKEN, timestamp, DingMsgSignUtils.getTimestampSign(timestamp, SIGN_SECRET));
        client = new DefaultDingTalkClient(URL);
        return client;

    }
}
